<?php

namespace Blogger\BlogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Blogger\BlogBundle\Entity\Consulta;
use Blogger\BlogBundle\Form\ConsultaType;

/**
 * @Route("/")
 */
class PageController extends Controller {

    /**
     * @Route("",name="index")
     *  
     */
    public function indexAction() {
        
        $em = $this->getDoctrine()->getEntityManager();
        $blogs = $em->getRepository('BloggerBlogBundle:Blog')->getLatestBlogs(3);
        return $this->render('BloggerBlogBundle:Page:index.html.twig',array('blogs'=>$blogs));
    }

    /**
     * 
     * @Route("about",name="about")
     */
    public function aboutAction() {
        return $this->render('BloggerBlogBundle:Page:about.html.twig');
    }

    /**
     * @Route("contact", name="contact")
     *      
     */
    public function contactAction() {
        $consulta = new Consulta();
        $form = $this->createForm(new ConsultaType(), $consulta);
        $request = $this->getRequest();
        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);
            if ($form->isValid()) {
                $message = \Swift_Message::newInstance()
                        ->setSubject($consulta->getSubject())
                        ->setFrom('symblog.dev@gmail.com')
                        ->setTo($consulta->getEmail())
                        ->setBody(
                                $this->renderView('BloggerBlogBundle:Page:mail.txt.twig',
                                        array('nombre'=>$consulta->getName()
                                )
                         ));
                
                $this->get('mailer')->send($message);

                $this->get('session')->setFlash('blogger-notice', 'Your contact enquiry was successfully sent. Thank you!');

                // Redirige - Esto es importante para prevenir que el usuario
                // reenvíe el formulario si actualiza la página
                return $this->redirect($this->generateUrl('contact'));
            }
        }

        return $this->render('BloggerBlogBundle:Page:contact.html.twig', array('form' => $form->createView()));
    }

}
